<?php

/**

 * 代小程序实现功能

 */

namespace app\common\helper\open;

use app\common\model\ShopModel; 

use app\common\model\AppVersionModel;

use app\common\logic\DataSettingLogic;

use think\facade\Db;



class OpenPlatformMiniappHelper extends OpenPlatformBaseHelper{

    

    protected $shopId;

    protected $shopInfo;





    public function  _init(){

        $this->setTicket();

    }

    

    /**

     * @param object $param 可以是shop_id 或者是shopInfo;

     * @return  $this 返回本身

     */

    public function setShopId($param){

        if(is_numeric($param)){

            $this->shopId = $param; 

            $this->shopInfo = ShopModel::find($param);

        }else{

            $this->shopInfo = $param;

            $this->shopId   = $param->shop_id;

        }

        return $this;

    }

   

    /**

     * 体验二维码获取

     */

    public function  getTestQrcode($path){

        $miniProgram = $this->app->miniProgram($this->shopInfo->wx_app_id,$this->shopInfo->wx_refresh_token);

        return $miniProgram->code->getQrCode($path);

    }

    

    /**

     * 生成二维码

     */

    public function getQrcode($path){

        $miniProgram = $this->app->miniProgram($this->shopInfo->wx_app_id,$this->shopInfo->wx_refresh_token);

        return $miniProgram->app_code->get($path);

    }



    public function refresh_token(){

        $miniProgram = $this->app->miniProgram($this->shopInfo->wx_app_id,$this->shopInfo->wx_refresh_token);

        return $miniProgram->access_token->getToken();

    }

    public function mp_refresh_token(){

        $miniProgram = $this->app->miniProgram($this->shopInfo->mp_appid,$this->shopInfo->mp_refresh_token);

        return $miniProgram->access_token->getToken();

    }

    

    /**

     * 获取授权地址

     * @param string $callback 返回的地址

     * @return string $url 授权跳转的地址

     */

    

    public function getAuthUrl($callback,$type){

        $url = $this->app->getPreAuthorizationUrl($callback);

        return $url.'&auth_type='.$type;



    }

   

    /**

     * 小程序-授权登录扫码后返回 使用之前调用 setShopId

     * @param string $authCode 授权返回的aut_code

     * @return bool 

     */

    public function authCallback($authCode){

        $datas = $this->app->handleAuthorize($authCode);

        if(empty($datas['authorization_info'])){

            return false;

        }

        $appinfo = $this->app->getAuthorizer($datas['authorization_info']['authorizer_appid']);

        if(empty($appinfo['authorizer_info'])){

            return false;

        }

        $this->shopInfo->status = 1;

        $this->shopInfo->wx_app_id = $datas['authorization_info']['authorizer_appid'];

        $this->shopInfo->wx_auth_key = $datas['authorization_info']['authorizer_access_token'];

        $this->shopInfo->wx_refresh_token = $datas['authorization_info']['authorizer_refresh_token'];

        $this->shopInfo->wx_face = $appinfo['authorizer_info']['head_img'] ?? ''; //新公众帐号没有

        $this->shopInfo->wx_name = $appinfo['authorizer_info']['nick_name'] ?? '';

        $this->shopInfo->wx_app_open_id = $appinfo['authorizer_info']['user_name'];

        $this->shopInfo->wx_principal_name = $appinfo['authorizer_info']['principal_name'];

        $this->shopInfo->code_status = 0;//重新授权后将代码的状态改成0

        $this->shopInfo->save();

        return true;

    }



    /**

     * 公众号-授权登录扫码后返回 使用之前调用 setShopId

     * @param string $authCode 授权返回的aut_code

     * @return bool

     */

    public function mpauthCallback($authCode){

        $datas = $this->app->handleAuthorize($authCode);

        if(empty($datas['authorization_info'])){

            return false;

        }

        $appinfo = $this->app->getAuthorizer($datas['authorization_info']['authorizer_appid']);

        if(empty($appinfo['authorizer_info'])){

            return false;

        }

        $this->shopInfo->mp_status = 1;

        $this->shopInfo->mp_appid = $datas['authorization_info']['authorizer_appid'];

        $this->shopInfo->mp_auth_key = $datas['authorization_info']['authorizer_access_token'];

        $this->shopInfo->mp_refresh_token = $datas['authorization_info']['authorizer_refresh_token'];

        $this->shopInfo->mp_face = $appinfo['authorizer_info']['head_img'] ?? ''; //新公众帐号没有

        $this->shopInfo->mp_name = $appinfo['authorizer_info']['nick_name'] ?? '';

        $this->shopInfo->mp_app_open_id = $appinfo['authorizer_info']['user_name'];

        $this->shopInfo->mp_principal_name = $appinfo['authorizer_info']['principal_name'];

        $this->shopInfo->save();

        return true;

    }

    

    /**

     * 获取手机号码 调用前要调用setShopId

     * @param array $code $iv $encryptedData $mdata $miv

     * @return array

     */

    

    public function getUserInfo($param){

        $return = [];

        if(empty($param['code'])){

            return false;

        }

        $miniProgram = $this->app->miniProgram($this->shopInfo->wx_app_id,$this->shopInfo->wx_refresh_token);
        $session = $miniProgram->auth->session($param['code']); //用CODE 换session_key
    
        if(empty($session['session_key']) && empty($session['openid'])){
            return false;
        }

        $return['openid'] = $session['openid']; //openId
        $return['mobile'] = '';
        if(!empty($param['iv']) && !empty($param['encryptedData'])){
            $codeDatas = $miniProgram->encryptor->decryptData($session['session_key'],$param['iv'],$param['encryptedData']);
            if(!empty($codeDatas['phoneNumber'])){
                $return['mobile'] = $codeDatas['phoneNumber'];
            }
        }
        return $return;

    }
    

    /**

     * 上传代码 使用之前调用 setShopId

     * @return bool

     */

    public function upload(){

        $DataSettingLogic = new DataSettingLogic();

        $oss = $DataSettingLogic->getData('oss');

        $baseUrl = rtrim(env('domain.base_url','https://i.uumo.top/'),'\/');
        $mapUrl = rtrim('https://apis.map.qq.com/','\/');

        $imgUrl = rtrim($oss['domain'],'\/');

        $miniProgram = $this->app->miniProgram($this->shopInfo->wx_app_id,$this->shopInfo->wx_refresh_token); 
        $domain = [

            'action'        => 'set',

            'requestdomain' => [$baseUrl,$mapUrl,$imgUrl],

            'wsrequestdomain' => [],

            'uploaddomain'  => [$baseUrl],

            'downloaddomain' => [$baseUrl,$imgUrl],

        ];

        $res = $miniProgram->domain->modify($domain);


        if($res['errcode'] != 0){

            return $res['errmsg'];

        }

        $AppVersionModel = new AppVersionModel();
        if($this->shopInfo->shop_id==35){//平台版小程序发布
            $version  = $AppVersionModel->where('app_id', 6)->order(['v'=>'desc'])->find();
        }else{
            $version  = $AppVersionModel->where('app_id', $this->shopInfo->app_id)->order(['v'=>'desc'])->find();
        }
        if(empty($version)){

            return '暂未发布模版';

        }

        $commit = [

            'template_id' => $version->template,

            'ext_json'    =>'{"extEnable":true,"extAppid":"'.$this->shopInfo->wx_app_id.'","ext":{"shopId":"'.$this->shopInfo->shop_id.'","wxAppId":"'.$this->shopInfo->wx_app_id.'","apiUrl":"'.$baseUrl.'/","staticUrl":"'.$imgUrl.'/static/"},"extPages":{},"networkTimeout":{"request":10000,"downloadFile":10000}}',

            'user_version' => 'V'.$version->v,

            'user_desc'  => $version->content,

        ];

        $res =  $miniProgram->code->commit($commit['template_id'], $commit['ext_json'], $commit['user_version'], $commit['user_desc']);

        if($res['errcode'] != 0){
             return $res['errmsg'];

        }

        $this->shopInfo->v = $version->v;

        $this->shopInfo->code_status = 1;

        $this->shopInfo->save();

        return true;

    }

    

    /**

     * 获取小程序的分类

     * @return array

     */

    

    public function getCategories(){

        $miniProgram = $this->app->miniProgram($this->shopInfo->wx_app_id,$this->shopInfo->wx_refresh_token); 

        $cats = $miniProgram->setting->getCategories();

        if($cats['errcode'] != 0){

            return false;

        }

        return $cats['categories'];

    }

    

    

    /**

     * 提交审核 使用之前调用 setShopId

     * @param array $datas

     * @return bool

     */

    

    public function  submit($datas){

        $miniProgram = $this->app->miniProgram($this->shopInfo->wx_app_id,$this->shopInfo->wx_refresh_token); 

        if(    empty($datas['tag']) || empty($datas['first_class']) 

            || empty($datas['second_class']) || empty($datas['first_id'])

            || empty($datas['second_id'])    || empty($datas['title'])     

        ) return false;

        $audit = [

           [

               'address' => 'pages/client/index',

               'tag'     => $datas['tag'],

               'first_class' => $datas['first_class'],

               'second_class'=> $datas['second_class'],

               'first_id' => $datas['first_id'],

               'second_id' => $datas['second_id'],

               'title' => $datas['title'],

           ]

        ]; 

        $res = $miniProgram->code->submitAudit($audit);

        if($res['errcode'] != 0){

             return $res['errmsg'];

        }

        if($this->shopInfo->status == 8){

            $this->shopInfo->is_upgrade = 1;

        }

        $this->shopInfo->code_status = 2;

        $this->shopInfo->save();

        return true;

    }

    

    /**

     * 回退审核，将会回退到 code_status = 0 的状态 使用之前调用 setShopId

     * @return bool

     */

    

    public function back(){

        $miniProgram = $this->app->miniProgram($this->shopInfo->wx_app_id,$this->shopInfo->wx_refresh_token); 

        $res = $miniProgram->code->withdrawAudit();

        if($res['errcode'] != 0){

            return $res['errmsg'];

        }

        $this->shopInfo->code_status = 0; //返回到等待上传代码

        $this->shopInfo->save();

        return true;

    }

    

    /**

     * 发布上线 使用之前调用 setShopId

     * @return bool

     */

    public function  online(){

        $miniProgram = $this->app->miniProgram($this->shopInfo->wx_app_id,$this->shopInfo->wx_refresh_token); 

        

//        $res  = $miniProgram->url_scheme->generate([

//            'is_expire'=> false,

//            'jump_wxa' =>[

//                'path' => '/pages/client/index',

//            ],

//        ]);

//        if($res['errcode'] != 0){

//            return $res['errmsg'];

//        }

//        //增加urlscheme

//        $this->shopInfo->urlscheme = $res['openlink'] ?? '';

        

        $res = $miniProgram->code->release();

        if($res['errcode'] != 0){

            return $res['errmsg'];

        }

        $this->shopInfo->status = 8;

        $this->shopInfo->code_status = 8;

        $this->shopInfo->save();

        return true;

    }



    

}
